package operation;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class TomcatManageDao {
	private static String ip;
	private static String user;
	private static String password;
	static{
		try (InputStream inputStream = TomcatManageDao.class.getResource("/ServerConfig.properties").openStream();
			 //InputStream inputStream = new FileInputStream(System.getProperty("user.dir")+"/ServerConfig.properties");
				){
			Properties properties = new Properties();
			properties.load(inputStream);
			ip = Objects.toString(properties.get("server.ip"));
			user = Objects.toString(properties.get("server.name"));
			password = Objects.toString(properties.get("server.password"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private Session session;

	public ChannelExec createChannelExec() throws JSchException{
		return (ChannelExec)getSession().openChannel("exec");
	}
	public ChannelSftp createChannelSftp() throws JSchException{
		return (ChannelSftp)getSession().openChannel("sftp");
	}
	private Session getSession() throws JSchException{
		if(null == session || !session.isConnected()){
			session = createSession();
		}
		return session;
	}
	private Session createSession() throws JSchException {
		JSch jSch = new JSch();
		Session session = jSch.getSession(user, ip);
		session.setPassword(password);
		Properties sshConfig = new Properties();
		sshConfig.put("StrictHostKeyChecking", "no");
		session.setConfig(sshConfig);
		session.connect();
		return session;
	}
	public void close() throws JSchException {
		getSession().disconnect();
	}

	
}
